package com.whj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whj.domain.constants.SystemConstants;
import com.whj.domain.entity.Link;
import com.whj.domain.entity.User;
import com.whj.domain.enums.AppHttpCodeEnum;
import com.whj.domain.response.ResponseResult;
import com.whj.domain.vo.LinkVo;
import com.whj.domain.vo.PageVo;
import com.whj.exception.SystemException;
import com.whj.mapper.LinkMapper;
import com.whj.service.LinkService;
import com.whj.utils.BeanCopyUtils;
import com.whj.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 友链(Link)表服务实现类
 *
 * @author wanghaijun
 * @since 2023-05-23 11:56:38
 */
@Service
public class LinkServiceImpl extends ServiceImpl<LinkMapper, Link> implements LinkService {

    @Override
    public ResponseResult getAllLink() {

        //查询所有审核通过的
        LambdaQueryWrapper<Link> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Link::getStatus, SystemConstants.LINK_STATUS_NORMAL);
        List<Link> list = list(queryWrapper);
        //转化vo
        List<LinkVo> linkVos = BeanCopyUtils.copyBeanList(list, LinkVo.class);
        //封装返回
        return ResponseResult.okResult(linkVos);
    }

    /**
     * 分页查询友链列表
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @param status
     * @return
     */
    @Override
    public ResponseResult selectLinkByPage(Integer pageNum, Integer pageSize, String name, String status) {

        LambdaQueryWrapper<Link> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(name), Link::getName, name);
        wrapper.eq(StringUtils.hasText(status), Link::getStatus, status);

        Page<Link> page = new Page<>(pageNum, pageSize);
        page(page, wrapper);
        return ResponseResult.okResult(new PageVo(page.getRecords(), page.getTotal()));
    }

    @Autowired
    private LinkMapper linkMapper;

    /**
     * 新增友链功能
     *
     * @param link
     * @return
     */
    @Transactional
    @Override
    public ResponseResult addLink(Link link) {
        if (linkNameExist(link.getName(),link.getId())) {
            throw new SystemException(AppHttpCodeEnum.NAME_IS_EXISTS);
        }
        if (urlExist(link.getAddress(),link.getId())) {
            throw new SystemException(AppHttpCodeEnum.URL_IS_EXISTS);
        }
        link.setDelFlag(0);
        linkMapper.insert(link);
        return ResponseResult.okResult();
    }

    /**
     * 修改友链
     *
     * @param link
     * @return
     */
    @Override
    public ResponseResult updateLink(Link link) {
        if (linkNameExist(link.getName(),link.getId())) {
            throw new SystemException(AppHttpCodeEnum.NAME_IS_EXISTS);
        }
        if (urlExist(link.getAddress(),link.getId())) {
            throw new SystemException(AppHttpCodeEnum.URL_IS_EXISTS);
        }
        linkMapper.updateById(link);
        return ResponseResult.okResult();
    }

    /**
     * 删除友链
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public ResponseResult delete(List<String> id) {
        if (SecurityUtils.isAdmin()){
            List<Long> collect = id.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            linkMapper.deleteBatchIds(collect);
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.NOT_ALLOW);
    }

    /**
     * 查询友链
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult selectLinkById(Long id) {
        Link link = linkMapper.selectById(id);
        return ResponseResult.okResult(link);
    }

    /**
     * 修改 状态
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public ResponseResult changeStatus(Long id, String status) {
        Link link = linkMapper.selectById(id);
        link.setStatus(status);
        linkMapper.updateById(link);
        return ResponseResult.okResult();
    }


    private boolean linkNameExist(String name, Long id) {
        LambdaQueryWrapper<Link> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Link::getName, name);
        Link link = linkMapper.selectOne(queryWrapper);
        if (!StringUtils.isEmpty(link)) {
            Long idDB = link.getId();
            if (!id.equals(idDB)) {
                return true;
            }
        }
        return false;
    }

    private boolean urlExist(String url, Long id) {
        LambdaQueryWrapper<Link> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Link::getAddress, url);
        Link link = linkMapper.selectOne(queryWrapper);

        if (!StringUtils.isEmpty(link)) {
            Long idDB = link.getId();
            if (!id.equals(idDB)) {
                return true;
            }
        }
        return false;
    }
}
